﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#if DOT_NET
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#endif
using StyleMVVM.UnitTests.TestClasses.SimpleObjects;
using StyleMVVM.DependencyInjection;
using StyleMVVM.Utilities;

namespace StyleMVVM.UnitTests.DependencyInjection
{
	[TestClass]
	public class CachedImportTests : BaseTestClass
	{
		[TestMethod]
		public void AbsoluteExpireTest()
		{
#if NETFX_CORE
			CacheManager.DefaultInstance.CollectionFrequency = new TimeSpan(0, 0, 0, 0, 500);
#endif

			CachedImportClass importClass = Container.Locate("CachedImportClass") as CachedImportClass;

			Assert.IsNotNull(importClass);
			Assert.IsNotNull(importClass.AbsoluteCached);

			AutoResetEvent resetEvent = new AutoResetEvent(false);

			resetEvent.WaitOne(1000);

			CachedImportClass importClass2 = Container.Locate("CachedImportClass") as CachedImportClass;

			Assert.IsNotNull(importClass2);
			Assert.IsNotNull(importClass2.AbsoluteCached);

			Assert.AreEqual(importClass.AbsoluteCached, importClass2.AbsoluteCached);

			resetEvent.WaitOne(30000);

			CachedImportClass importClass3 = Container.Locate("CachedImportClass") as CachedImportClass;

			Assert.IsNotNull(importClass3);
			Assert.IsNotNull(importClass3.AbsoluteCached);

			Assert.AreNotEqual(importClass.AbsoluteCached, importClass3.AbsoluteCached);
		}

		[TestMethod]
		public void SlidingExpireTest()
		{
#if NETFX_CORE
			CacheManager.DefaultInstance.CollectionFrequency = new TimeSpan(0, 0, 0, 0, 500);
#endif

			CachedImportClass importClass = Container.Locate("CachedImportClass") as CachedImportClass;

			Assert.IsNotNull(importClass);
			Assert.IsNotNull(importClass.SlidingWindowCached);

			AutoResetEvent resetEvent = new AutoResetEvent(false);

			for (int i = 0; i < 40; i++)
			{
				resetEvent.WaitOne(1000);

				CachedImportClass importClass2 = Container.Locate("CachedImportClass") as CachedImportClass;

				Assert.IsNotNull(importClass2);
				Assert.IsNotNull(importClass2.SlidingWindowCached);

				Assert.AreEqual(importClass.SlidingWindowCached, importClass2.SlidingWindowCached);
			}

			resetEvent.WaitOne(31000);

			CachedImportClass importClass3 = Container.Locate("CachedImportClass") as CachedImportClass;

			Assert.IsNotNull(importClass3);
			Assert.IsNotNull(importClass3.SlidingWindowCached);

			Assert.AreNotEqual(importClass.SlidingWindowCached, importClass3.SlidingWindowCached);
		}
	}
}